package com.lninl.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.filter.HttpPutFormContentFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.FilterRegistration.Dynamic;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

public class WebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext)
            throws ServletException {
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(WebConfiguration.class);
        rootContext.setDisplayName("Markme");
        servletContext.addListener(new ContextLoaderListener(rootContext));
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
                "dispatcher", new DispatcherServlet(rootContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");

        Dynamic filter = servletContext.addFilter("characterEncodingFilter",
                CharacterEncodingFilter.class);
        filter.addMappingForUrlPatterns(null, false, "/*");
        filter.setInitParameter("encoding", "UTF-8");
        filter.setInitParameter("forceEncoding", "true");

        Dynamic securityFilter = servletContext.addFilter("shiroFilter",
                DelegatingFilterProxy.class);
        filter.addMappingForUrlPatterns(null, false, "/*");
        filter.setInitParameter("targetFilterLifecycle", "true");


        servletContext.addFilter("hiddenHttpMethodFilter",
                HiddenHttpMethodFilter.class).addMappingForUrlPatterns(null,
                false, "/*");

        servletContext.addFilter("httpPutFormContentFilter", HttpPutFormContentFilter.class);
    }
}
